﻿package action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.junit.runner.Request;

import model.Commodity;
import model.Indent;

import daoJDBC.interfaceDO.serviceDO.Do_IDUS;


public class MainServlet extends HttpServlet{

	//创建操作数据库的对象
	Do_IDUS idus=new Do_IDUS();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//获取前台传过来的操作意向
		String option=req.getParameter("option");
		//判断选择需要的方法
		if (option.equals("login")) {
			insert(req,resp);
		}else if (option.equals("enter")) {
			enter(req,resp);
		}else if (option.equals("selectOne")) {
			selectOne(req,resp);
		}else if (option.equals("delete")) {
			delete(req,resp);
		}else if (option.equals("update_q")) {
			update_q(req,resp);
		}else if (option.equals("update")) {
			update(req,resp);
		}else if (option.equals("select")) {
			select(req,resp);
		}else if(option.equals("getout")){
			getout(req,resp);
		}else if(option.equals("newsc")){
			newsc(req,resp);
		}
	}
	//新增\
	public void newsc(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----newsc----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		req.getSession().removeAttribute("list");
		String ta_name=req.getParameter("ta");
		if (ta_name.equals("smallclass")) {
			List list_big=idus.select("bigclass", 0);
//			System.out.println(list_big);
			req.getSession().setAttribute("list_big", list_big);
			resp.sendRedirect("houtai/newsmall.jsp");
		}else if (ta_name.equals("commodity")) {
			List list_small=idus.select("smallclass", 0);
			req.getSession().setAttribute("list_small", list_small);
			resp.sendRedirect("houtai/newcommodity.jsp");
		}
	}

	public void getout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----退出登陆--");
		req.getSession().removeAttribute("adminName");
		resp.sendRedirect("houtai/homePage.html");
	}

	//登陆
	public void enter(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("----enter----");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw=resp.getWriter();
		String ta_name=req.getParameter("ta");//传入要查询的是哪一张表
		String adminName=req.getParameter("adminName");
		String password=req.getParameter("password");
		ResultSet rs=idus.enterSelect(ta_name,adminName, password);
		if (rs!=null) {
			System.out.println("管理员登陆成功，可跳转进入系统首页去执行其他操作");
			req.getSession().setAttribute("adminName",adminName);
			System.out.println("---管理员---"+adminName);
			resp.sendRedirect("houtai/ManagerHome.html");
		}else {
			pw.print("密码或用户名不正确，请重新登陆----<a href='houtai/homePage.jsp'>返回</a>");
		}
	}

	//查找所有
	public void select(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("--------query");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		HttpSession sess=req.getSession();
		String ta_name=req.getParameter("ta");
		System.out.println("---查找的表---"+ta_name);
		//获取前台传入的当前页，作为查询参数去执行查询语句，返回结果集合list
		int tpage=Integer.parseInt(req.getParameter("tpage"));
		System.out.println("当前页----"+tpage);
		List list=idus.select(ta_name, tpage);
		if (list!=null&&list.size()!=0) {
			sess.setAttribute("list", list);//将结果集合保存到容器中，在结果页面去遍历输出
			int allUser=idus.getAllUser(ta_name);
			sess.setAttribute("allUser", allUser);//获取用户总数保存到容器中，结果页面需要数值
			System.out.println("总用户----"+allUser);
			int apage=idus.getApage(ta_name);
			sess.setAttribute("apage", apage);//获取总页数保存到容器中，传到结果页面用于操作
			System.out.println("总页数----"+apage);
			sess.setAttribute("tpage", tpage);//将当前页保存到容器中，传到结果页面
			if (ta_name.equals("bigclass")) {//跳转大分类管理页面
				resp.sendRedirect("houtai/bigclass.jsp");
			}else if (ta_name.equals("smallclass")) {//跳转小分类管理页面
				resp.sendRedirect("houtai/smallclass.jsp");
			}else if (ta_name.equals("notice")) {//跳转公告管理页面
				resp.sendRedirect("houtai/notice.jsp");
			}else if (ta_name.equals("user")) {//跳转用户管理页面
				resp.sendRedirect("houtai/usermanager.jsp");
			}else if (ta_name.equals("indent")) {//跳转订单管理页面
				resp.sendRedirect("houtai/indent.jsp");
			}else if (ta_name.equals("commodity")) {//跳转用户管理页面
				resp.sendRedirect("houtai/commodity.jsp");
			}
		}else {
			System.out.println("list为空，无查询结果");
		}
	}

	//修改
	public void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("--------update");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw=resp.getWriter();
		req.getSession().removeAttribute("list");
		String ta_name=req.getParameter("ta");
		int i=-1;
		if (ta_name.equals("bigclass")) {//修改大分类
			int id=Integer.parseInt(req.getParameter("thisID"));
			String bigclassName=req.getParameter("bigclassName");
			String sql="update bigclass set bigclassName=? where id=?";
			i=idus.update(sql, new Object[]{bigclassName,id});
			if (i>0) {
				System.out.println("---修改成功");
				resp.sendRedirect("MainServlet?option=select&ta=bigclass&tpage=1");
			}
		}else if (ta_name.equals("smallclass")) {//修改小分类
			int id=Integer.parseInt(req.getParameter("thisID"));
			String smallclassName=req.getParameter("smallclassName");
			String bigclassName=req.getParameter("bigclassName");
			String sql="update smallclass set smallclassName=?,bigclassName=? where id=?";
			i=idus.update(sql, new Object[]{smallclassName,bigclassName,id});
			if (i>0) {
				System.out.println("---修改成功");
				resp.sendRedirect("MainServlet?option=select&ta=smallclass&tpage=1");
			}
		}else if(ta_name.equals("user")){//修改用户
			int id=Integer.parseInt(req.getParameter("thisID"));
			String account=req.getParameter("account");
			String name=req.getParameter("name");
			String password=req.getParameter("password");
			String sex=req.getParameter("sex");
			String birth=req.getParameter("birth");
			String cardID=req.getParameter("cardID");
			String email=req.getParameter("email");
			String cellphone=req.getParameter("cellphone");
			String address=req.getParameter("address");
			String sql="update user set account=?,name=?,password=?,sex=?,birth=?,cardID=?,email=?,cellphone=?,address=? where id=?";
			Object[] obj=new Object[]{account,name,password,sex,birth,cardID,email,cellphone,address,id};
			i=idus.update(sql, obj);
			if (i>0) {
				System.out.println("---修改成功");
				resp.sendRedirect("MainServlet?option=select&ta=user&tpage=1");
			}
		}else if (ta_name.equals("indent")) {//修改订单
			int id=Integer.parseInt(req.getParameter("id"));
			String userName=req.getParameter("userName");
			String userAddress=req.getParameter("userAddress");
			double amount=Double.parseDouble(req.getParameter("amount"));
//			System.out.println("--->>>>>>"+amount);
			String indentDate=req.getParameter("indentDate");
			String indentStatus=req.getParameter("indentStatus");
			String sql="update indent set userName=?,userAddress=?,amount=?,indentDate=?,indentStatus=? where id=?";
			Object []obj=new Object[]{userName,userAddress,amount,indentDate,indentStatus,id};
			i=idus.update(sql, obj);
			if (i>0) {
				System.out.println("---修改成功");
				resp.sendRedirect("MainServlet?option=select&ta=indent&tpage=1");
			}
		}else if (ta_name.equals("notice")) {//修改公告
			int id=Integer.parseInt(req.getParameter("thisID"));
			String noticeTitle=req.getParameter("noticeTitle");
			String noticeContent=req.getParameter("noticeContent");
			String sql="update notice set noticeTitle=?,noticeContent=? where id=?";
			i=idus.update(sql, new Object[]{noticeTitle,noticeContent,id});
			if (i>0) {
				System.out.println("---修改成功");
				resp.sendRedirect("MainServlet?option=select&ta=notice&tpage=1");
			}
		}else if (ta_name.equals("commodity")) {//修改商品详情
			//创建工厂对象
			DiskFileItemFactory factory=new DiskFileItemFactory();
			//创建解析对象
			ServletFileUpload sfu=new ServletFileUpload(factory);
			//解析请求
			Map map=new HashMap();	boolean b=false;	
			try {
				List listfl = sfu.parseRequest(req);
				
				for (int k = 0; k < listfl.size(); k++) {
					FileItem file=(FileItem)listfl.get(k);
					if (file.isFormField()) {//判断获得的表单文件是否是普通文本
						String name=file.getFieldName();//获取name的值
						String value=file.getString("utf-8");//获取表单中的value值，加字符编码是为了防止乱码
						System.out.println(name+"----"+value);
						map.put(name, value);//存入MAP集合中
					}else {//不是普通文本说明是上传文件 ，上传文件用另一种获取方式 
						String name=file.getFieldName();//同样是获取name的值 
						String fileName=file.getName();//获取上传的文件的文件名
						System.out.println(name+"----"+fileName);//查看一下上传的文件 名
						if (!fileName.equals("")) {//文件名不为空则保存文件 
							String path=getServletContext().getRealPath("commodityPicture");//获得文件的保存路径
							System.out.println(path);//文件的保存路径
							String imgName=UUID.randomUUID().toString()+"_"+fileName;
							System.out.println(imgName);
							file.write(new File(path, imgName));
							String image="commodityPicture\\"+imgName;
							map.put(name, image);
							b=true;
						}
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String sql="";Object obj[]=null;
			if (b) {
				sql="update commodity set commodityName=?,smallclassName=?,sale=?,num=?,picture=? where id=?";
				obj=new Object[]{
						map.get("commodityName"),	
						map.get("smallclassName"),	
						map.get("sale"),	
						map.get("num"),	
						map.get("picture"),
						map.get("id")
				};
			}else {
				sql="update commodity set commodityName=?,smallclassName=?,sale=?,num=? where id=?";
				obj=new Object[]{
						map.get("commodityName"),	
						map.get("smallclassName"),	
						map.get("sale"),	
						map.get("num"),	
						map.get("id")
				};
			}
			i=idus.update(sql, obj);
			if (i>0) {
				System.out.println("---修改成功");
				resp.sendRedirect("MainServlet?option=select&ta=commodity&tpage=1");
			}
		}
	}

	//修改前的反馈
	public void update_q(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("--------update_q");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		HttpSession session=req.getSession();
			int thisID=Integer.parseInt(req.getParameter("thisID"));
			System.out.println("---要修改的ID--"+thisID);
			String ta_name=req.getParameter("ta");
			List list=idus.selectOne(ta_name, thisID);
//			for (User user : list) {
//				System.out.println("要修改的用户："+user);
//			}
			if (list!=null) {
				session.setAttribute("list",list);
//			System.out.println(list.size());
				if (ta_name.equals("bigclass")) {//跳转大分类修改页面
					resp.sendRedirect("houtai/updateBig.jsp");
				}else if (ta_name.equals("smallclass")) {//跳转小分类修改页面
					List list_big=idus.select("bigclass", 0);
					session.setAttribute("list_big", list_big);
					resp.sendRedirect("houtai/updateSmall.jsp");
				}else if (ta_name.equals("notice")) {//跳转公告修改页面
					resp.sendRedirect("houtai/updateNotice.jsp");
				}else if (ta_name.equals("user")) {//跳转用户修改页面
					resp.sendRedirect("houtai/updateUser.jsp");
				}else if (ta_name.equals("indent")) {//跳转订单修改页面
//					Indent in=(Indent) session.getAttribute("list");
//					System.out.println("--要修改的订单内容--"+in.getAmount());
					resp.sendRedirect("houtai/updateIndent.jsp");
				}else if (ta_name.equals("commodity")) {//跳转商品修改页面
					List list_small=idus.select("smallclass", 0);
					session.setAttribute("list_small", list_small);
					resp.sendRedirect("houtai/updateCommodity.jsp");
				}
			}else {
				System.out.println("-------");
			}
	}

	//删除
	public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("--------delete");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw=resp.getWriter();
		int id=Integer.parseInt(req.getParameter("thisID"));
		String ta_name=req.getParameter("ta");
		int tpage=Integer.parseInt(req.getParameter("tpage"));
		int i=idus.delete(ta_name, id);
		if(i>0){
			System.out.println("删除成功");
			resp.sendRedirect("MainServlet?option=select&ta="+ta_name+"&tpage="+tpage);
		}else{
			System.out.println("删除失败");
//			pw.print("删除失败----<a href='MainServlet?option=select&thisID=0'>返回</a>");
		}
	}

	public void selectOne(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("--------selectOne");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw=resp.getWriter();
		int thisID=Integer.parseInt(req.getParameter("thisID"));
		String ta_name=req.getParameter("ta");
		System.out.println("--要查找的用户ID--"+thisID);
		List list=idus.selectOne(ta_name,thisID);
		if (list!=null&&list.size()!=0) {
				req.getSession().setAttribute("list", list);
				resp.sendRedirect("queryOne_result.jsp");
		}else{
			pw.print("查无此用户----<a href='query.jsp'>返回</a>");
		}
	}

	//添加
	public void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		System.out.println("--------insert------");
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		req.getSession().removeAttribute("list");
		String ta_name=req.getParameter("ta");
		int i=-1;
		if (ta_name.equals("bigclass")) {//大分类
			String bigclassName=req.getParameter("bigclassName");System.out.println("--新增大分类名-"+bigclassName);
			String sql="insert into bigclass set bigclassName=?";
			i=idus.insert(sql, new Object[]{bigclassName});
			if (i>0) {
				//跳转查询页面
				resp.sendRedirect("MainServlet?option=select&ta=bigclass&tpage=1");
			}
		}else if (ta_name.equals("smallclass")) {//小分类
			String smallclassName=req.getParameter("smallclassName");
			String bigclassName=req.getParameter("bigclassName");
			String sql="insert into smallclass set smallclassName=?,bigclassName=?";
			i=idus.insert(sql, new Object[]{smallclassName,bigclassName});
			if (i>0) {
				//跳转查询页面
				resp.sendRedirect("MainServlet?option=select&ta=smallclass&tpage=1");
			}
		}else if (ta_name.equals("indent")) {//订单
			String userName=req.getParameter("username");
			String userAddress=req.getParameter("address");
			String userCellphone=req.getParameter("telnumber");
			double amount=(Double)req.getSession().getAttribute("amount");
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日");
			String indentDate=sdf.format(new Date());
			String sql="insert into indent set userName=?,userAddress=?,amount=?,userCellphone=?,indentDate=?";
			i=idus.insert(sql, new Object[]{userName,userAddress,amount,userCellphone,indentDate});
			if (i>0) {
				System.out.println("-订单提交成功--");
				idus.delete("shoppingcar", 0);
				req.getSession().removeAttribute("amount");
				req.getSession().removeAttribute("youhui");
				resp.sendRedirect("qiantai/indent_success.html");
			}
		}else if (ta_name.equals("notice")) {//公告
			String noticeTitle=req.getParameter("noticeTitle");
			String noticeContent=req.getParameter("noticeContent");
			String sql="insert into notice set noticeTitle=?,noticeContent=?";
			i=idus.insert(sql, new Object[]{noticeTitle,noticeContent});
			if (i>0) {
				//跳转查询页面
				resp.sendRedirect("MainServlet?option=select&ta=notice&tpage=1");
			}
		}else if (ta_name.equals("user")) {//用户
			String account=req.getParameter("account");
			String name=req.getParameter("name");
			String password=req.getParameter("password");
			String sex=req.getParameter("sex");
			String birth=req.getParameter("birth");
			String cardID=req.getParameter("cardID");
			String email=req.getParameter("email");
			String cellphone=req.getParameter("cellphone");
			String address=req.getParameter("address");
			String sql="insert into user(account,name,password,sex,birth,cardID,email,cellphone,address) values(?,?,?,?,?,?,?,?,?)";
			Object [] obj=new Object[]{account,name,password,sex,birth,cardID,email,cellphone,address};
			i=idus.insert(sql, obj);
			if (i>0) {
				//跳转查询页面
				resp.sendRedirect("MainServlet?option=select&ta=user&tpage=1");
			}
		}else if (ta_name.equals("commodity")) {
			//创建工厂对象
			DiskFileItemFactory factory=new DiskFileItemFactory();
			//创建解析对象
			ServletFileUpload sfu=new ServletFileUpload(factory);
			//解析请求
			Map map=new HashMap();	boolean b=false;	
			try {
				List listfl = sfu.parseRequest(req);
				
				for (int k = 0; k < listfl.size(); k++) {
					FileItem file=(FileItem)listfl.get(k);
					if (file.isFormField()) {//判断获得的表单文件是否是普通文本
						String name=file.getFieldName();//获取name的值
						String value=file.getString("utf-8");//获取表单中的value值，加字符编码是为了防止乱码
						System.out.println(name+"----"+value);
						map.put(name, value);//存入MAP集合中
					}else {//不是普通文本说明是上传文件 ，上传文件用另一种获取方式 
						String name=file.getFieldName();//同样是获取name的值 
						String fileName=file.getName();//获取上传的文件的文件名
						System.out.println(name+"----"+fileName);//查看一下上传的文件 名
						if (!fileName.equals("")) {//文件名不为空则保存文件 
							String path=getServletContext().getRealPath("commodityPicture");//获得文件的保存路径
							System.out.println(path);//文件的保存路径
							String imgName=UUID.randomUUID().toString()+"_"+fileName;
							System.out.println(imgName);
							file.write(new File(path, imgName));
							String image="commodityPicture\\"+imgName;
							map.put(name, image);
							b=true;
						}
					}
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String sql="";Object obj[]=null;
			if (b) {
				sql="insert into commodity set commodityName=?,smallclassName=?,oldSale=?,sale=?,num=?,picture=?,id=?";
				obj=new Object[]{
						map.get("commodityName"),	
						map.get("smallclassName"),
						map.get("oldSale"),
						map.get("sale"),	
						map.get("num"),	
						map.get("picture"),
						map.get("id")
				};
			}else {
				sql="insert into commodity set commodityName=?,smallclassName=?,oldSale=?,sale=?,num=?,id=?";
				obj=new Object[]{
						map.get("commodityName"),	
						map.get("smallclassName"),
						map.get("oldSale"),
						map.get("sale"),	
						map.get("num"),	
						map.get("id")
				};
			}
			i=idus.insert(sql, obj);
			if (i>0) {
				System.out.println("---添加成功");
				resp.sendRedirect("MainServlet?option=select&ta=commodity&tpage=1");
			}else {
				System.out.println("---添加失败");
				resp.sendRedirect("MainServlet?option=select&ta=commodity&tpage=1");
			}
		}		
	}
	
	
}
